#include "ui/PaintWidget.h"

#include <QRect>
#include <QPainter>
#include <QPaintEvent>
#include <QThread>

PaintWidget::PaintWidget(QWidget *parent) : QWidget(parent) {
    lastPosition = QPoint(-1, -1);
}

void PaintWidget::resizeEvent (QResizeEvent * event) {
    inputImage = QImage(event->size(), QImage::Format_RGB32);
    inputImage.fill(qRgb(255, 255, 255));
}

void PaintWidget::paintEvent(QPaintEvent */*event*/) {
    QPainter painter(this);
    painter.drawImage(QPoint(0, 0), inputImage);
}

void PaintWidget::mouseMoveEvent(QMouseEvent *event) {
    if (locked) {
        return;
    }
    QPoint newPosition = event->pos();
    if (newPosition.x() < 0) {
        newPosition.setX(0);
    }
    if (newPosition.y() < 0) {
        newPosition.setY(0);
    }
    if (newPosition.x() > inputImage.width() - 1) {
        newPosition.setX(inputImage.width() - 1);
    }
    if (newPosition.y() > inputImage.height() - 1) {
        newPosition.setY(inputImage.height() - 1);
    }

    QPainter painter(&inputImage);
    painter.setPen(QPen(paintColor));
    painter.drawLine(lastPosition, newPosition);

    lastPosition = newPosition;
    repaint();

    emit pointDrawed(lastPosition);
}

void PaintWidget::setLocked(bool value) {
    locked = value;
}

void PaintWidget::mousePressEvent(QMouseEvent *event) {
    if (locked) {
        return;
    }
    lastPosition = event->pos();
    emit pointDrawed(lastPosition);
}

void PaintWidget::mouseReleaseEvent(QMouseEvent */*event*/) {
    if (locked) {
        return;
    }
    lastPosition = QPoint(-1, -1);
    emit pointDrawed(lastPosition);
}

void PaintWidget::drawPaths(const QList<DrawPath *> * paths, QColor color) {
    QPainter painter(&inputImage);
    painter.setPen(QPen(color));
    for (int i = 0; i < paths->length(); ++i) {
        const QList<QPoint> pointList = paths->at(i)->getPointList();
        QPoint last = pointList.at(0);
        for (int j = 1; j < pointList.length(); ++j) {
            QPoint current = pointList.at(j);
            painter.drawLine(last, current);
            last = current;
        }
    }
    repaint();
}

void PaintWidget::imagePaint(const QImage & image) {
    inputImage = image.convertToFormat(QImage::Format_RGB32);
//    inputImage.save("/tmp/data", "png");
    repaint();
}
